<?php
// +----------------------------------------------------------------------
// | [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Author < 931274989@qq.com >
// +----------------------------------------------------------------------
// | Explain 处理接收回复消息
// +----------------------------------------------------------------------
namespace app\wechat\controller;

use EasyWeChat\Foundation\Application;
use EasyWeChat\Message\Text;
use think\facade\Config;
use think\Controller;
use app\model\User;
use think\Db;

class Accept extends Controller
{
  public function acceptMsg()
  {
    $options = Config::get('wewhat.wxConfig');
    $app = new Application($options);
    $server = $app->server;
    $server->setMessageHandler(function($message){
      $model = new User();
      // 处理接收文本消息0
      if($message->MsgType == 'text') {
        $text = new Text(['content' => $message->Content]);
        return $text;
      }

      // 当 $message->MsgType 为 event 时为事件
      if ($message->MsgType == 'event') {
        switch ($message->Event) {
          # 点击事件
          case 'CLICK':
          return $this->clickFun($message);
          break;
          # 关注事件
          case 'subscribe':
            $eventKey = $message->EventKey;
            $eventKey = (string)$eventKey;
            $openId = $message->FromUserName;
            $userid = $model->where('openid','=',$openId)->find();
            if( empty($userid) ){
              // 三级分销添加数据库
              if(empty($eventKey)){ //顶级添加数据库
                $model->save(['openid' => $openId]);
              } else {
                # 得到上级id
                $fid = str_replace('qrscene_','',$eventKey);
                // $fid = (int)$id;
                # 查询记录
                $row = $model->where('openid','=',$fid)->find();
                # 添加本人的记录数据
                $model->save([
                  'openid' => $openId,
                  'f1' => $row['openid'],
                  'f2' => $row['f1'],
                  'f3' => $row['f2']
                ]);
              }
            }
            return new Text(['content' => "您好，欢迎关注\n赤峰活动信息平台！"]);
            break;
          default:
            # code...
            break;
        }
      }
      
    });
    $response = $server->serve();
    $response->send(); 
  }

  //处理点击事件
  private function clickFun($message)
  {
    $eventKey = $message->EventKey;
    if( $eventKey == 'key001' ){
      $text = new Text(['content' =>
        "热线电话\n电话：0476-8490267\n手机：15304766245\n公司地址：内蒙古赤峰市松山区中昊大厦8楼845"]);
      return $text;
    }
  }
}
?>